import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

// 1. axios 创建实例
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 基地址
  timeout: 5000 // 超时时间
})

// 2.请求拦截器
request.interceptors.request.use(
  config => {
    // 2.1 判断token是否存在
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${getToken()}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 3. 响应拦截器
request.interceptors.response.use(
  (response) => {
    // 3.1解构数据
    const { code, data, msg } = response.data
    // 3.2 判断：请求成功且业务成功   / 请求成功但业务失败
    if (code === 10000) {
      return data
    } else {
      Message.error(msg)
      return Promise.reject(new Error(response))
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default request
